package com.heima.kafka.boot.kafkastream;

import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.kstream.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;
import java.util.Arrays;

/**
 * kafkastream的配置类，用来进行流式计算
 */
@Configuration
public class KSteamConfig {

    @Bean
    public KStream<String,String> kStream(StreamsBuilder streamsBuilder){
        //1.接收生产者发送的消息
        KStream<String, String> stream = streamsBuilder.stream("boot-kafkastream-topic1");
        //2.处理消息
        stream.flatMapValues(new ValueMapper<String, Iterable<String>>() {
            /**
             * 接收的消息：
             *      key=first0  value=hello kafka
             *      key=first1  value=hello itcast
             *
             * @param value
             * @return  ["hello","kafka","hello","itcast",....]
             */
            @Override
            public Iterable<String> apply(String value) {
                return Arrays.asList(value.split(" "));
            }
        })
                /**
                 * 表示分组聚合，key=first0 first1 ,....
                 * 此时的value就是 ["hello","kafka","hello","itcast",....]
                 *          分组之后就会出现三组，以hello一组，kafka一组，itcast一组
                 */
                .groupBy((key,value)-> value)//根据什么分组
                .windowedBy(TimeWindows.of(Duration.ofSeconds(10)))//每10s拉取一次消息内容
                .count()//求和，返回值是ktable类型
                .toStream()//把ktable类型转化成kstream类型
                /**
                 * 发送的消息内容
                 * key=hello  ,kafka, itcast
                 * value=2     2            2
                 */
                .map((KeyValueMapper<Windowed<String>, Long, KeyValue<String, String>>) (key, value) -> {
                    return new KeyValue<>(key.key().toString(),value.toString());
                })
                //第三步，发送消息，消息内容
                .to("boot-kafkastream-toipc2");//发送消息

        return stream;
    }
}
